/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include "main.h"
#include "bldc.h"
#include "debug_uart.h"
#include "key.h"
#include "adc.h"
#include "pid.h"
#include "debug.h"
#include "fdcan.h"


void SystemClock_Config(void);


/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
    int32_t pid_target_value_temp = 0;
    uint32_t cycle_num = 0;
    uint32_t old_speed = 0;
    HAL_Init();
    SystemClock_Config();
    debug_uart_init();
    key_init();
    adc_module_init();
    pid_init();
    bldc_init();
    fdcan_init();  // 初始化FDCAN

#if DEBUG_ENABLE
    debug_init();
    debug_send_motorcode(BLDC_MOTOR);           /* 直流无刷电机 */
    debug_send_motorstate(IDLE_STATE);          /* 电机空闲 */
    /* 初始化同步数据（选择第x组PIDX,目标速度地址,P,I,D参数）到上位机 */
    debug_send_initdata(TYPE_PID1, (float*)(&g_speed_pid.target_value), S_KP, S_KI, S_KD);/* 速度环PID参数（PID1）*/
#endif
    bldc_print_clock_info();
    // bldc_start();
    
    while (1)
    {
        uint8_t keyvalue = key_scan();

        if(keyvalue == KEY_0 || keyvalue == KEY_2)
        {
            if(keyvalue == KEY_2)
            {
                pid_target_value_temp+=200;
            }
            else if(keyvalue == KEY_0)
            {
                pid_target_value_temp-=200;
            }
            
            if(pid_target_value_temp>0)
            {
                bldc_set_motor_direction(FORWARD_ROTATION);
                pid_set_target_value(pid_target_value_temp);
                if(bldc_get_motor_status() == MOTOR_STOP)
                {
                    bldc_start();
                }
            } 
            else if(pid_target_value_temp<0) 
            {
                bldc_set_motor_direction(REVERSE_ROTATION);
                pid_set_target_value((uint32_t)abs(pid_target_value_temp));
                if(bldc_get_motor_status() == MOTOR_STOP)
                {
                    bldc_start();
                }
            } 
            else if(pid_target_value_temp==0)
            {
                bldc_stop();
            }
        }
        else if(keyvalue == KEY_1)
        {
            pid_target_value_temp = 0;
            bldc_stop();
        }
        
        if(fdcan_get_motor_start_request())
        {
            if(bldc_get_motor_status() == MOTOR_STOP)
            {
                bldc_start();
            }  
        }

        if(old_speed != g_bldc_motor1.speed)
        {
            old_speed = g_bldc_motor1.speed;
            fdcan_send_actual_speed(g_bldc_motor1.speed,g_bldc_motor1.dir);
        }
                
        

    
#if DEBUG_ENABLE
        /* Debug发送部分 */
        /* 主要显示参数 */
        debug_send_valtage(g_adc_val[0] * ADC2VBUS);                /* 发送电压 */
        debug_send_speed(g_bldc_motor1.speed);                      /* 发送速度 */
        // debug_send_temp(50, get_temp(g_adc_val[1]));                /* 发送电机温度、驱动板温度 */

        debug_send_wave_data(1, (int16_t)g_bldc_motor1.speed);      /* 选择通道1 发送实际速度 */
        debug_send_wave_data(2, g_speed_pid.target_value);           /* 选择通道2 发送目标 */
        debug_send_wave_data(3, g_bldc_motor1.current_u);                    /* 选择通道3 发送实际电流U */
        debug_send_wave_data(4, g_bldc_motor1.current_v);                    /* 选择通道4 发送实际电流V */
        debug_send_wave_data(5, g_bldc_motor1.current_w);                    /* 选择通道5 发送实际电流W */
        debug_send_wave_data(6, g_pid_inter.p_value);                    /* 选择通道6 pid 的比例项 */
        debug_send_wave_data(7, g_pid_inter.i_value);                    /* 选择通道7 pid 的积分项 */
        debug_send_wave_data(8, g_pid_inter.d_value);                    /* 选择通道8 pid 的微分项 */
        debug_send_wave_data(9, g_speed_pid.actual_value);                    /* 选择通道9 pid 输出总数*/
        debug_send_wave_data(10, g_bldc_motor1.pwm_duty);                    /* 选择通道10 发送实际pwm_duty	 */
        debug_send_wave_data(11, g_d_value_max_hold);                    /* 选择通道11 发送D项最大值*/
        debug_send_wave_data(12, g_d_value_min_hold);                    /* 选择通道12 发送D项最小值*/
        // debug_send_wave_data(13, g_speed_capture.capture_diff);  /* 选择通道13 发送捕获差值*/
        g_d_value_max_hold = -99999.0f;
        g_d_value_min_hold = 99999.0f;
        if (cycle_num % 100 == 0)
        {
            debug_receive_pid(TYPE_PID1,(float*)&g_speed_pid.proportion,/* 查询接收PID助手的PID1参数 */
                            (float*)&g_speed_pid.integral,(float*)&g_speed_pid.derivative);
            // printf("P:%f,I:%f,D:%f\r\n",g_speed_pid.proportion,g_speed_pid.integral,g_speed_pid.derivative);
        }
#else
        // if (cycle_num % 100 == 0)
        // {
        //     printf("\r\n");
        //     printf("prm:%d ,target:%f,duty:%d\r\n",g_bldc_motor1.speed,g_speed_pid.target_value,g_bldc_motor1.pwm_duty);
        //     printf("pid_inter:%f,%f,%f,%f\r\n",g_pid_inter.p_value,g_pid_inter.i_value,g_pid_inter.d_value,g_pid_inter.sum_value);
        //     printf("tick num:%d\r\n",motor_timer_tick);
        //     // debug_receive_pid(TYPE_PID1,(float*)&g_speed_pid.proportion,/* 查询接收PID助手的PID1参数 */
        //     //               (float*)&g_speed_pid.integral,(float*)&g_speed_pid.derivative);
        // }
#endif
         HAL_Delay(10);
         cycle_num++;
        
    }

}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1);

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV1;
  RCC_OscInitStruct.PLL.PLLN = 32;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
  RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK)
  {
    Error_Handler();
  }
}



/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler_Debug(const char* file, int line)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  printf("Error occurred in file: %s, line: %d\r\n", file, line);
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
